﻿using System.ComponentModel.DataAnnotations;
using System.Reflection;

namespace WenAntdUI.Forms
{
    public partial class TableEditForm : WenForm
    {
        public TableEditForm(object item, ItemChangedType itemChangedType)
        {
            InitializeComponent();

            this.StartPosition = FormStartPosition.CenterParent;
            Item = item;
            this.ChangedType = itemChangedType;

            this.Text = itemChangedType == ItemChangedType.Update ? "修改" : "新增";

            SetBox();

            this.modelEdit1.CancelClick += ModelEdit1_CancelClick;
            this.modelEdit1.OkClick += ModelEdit1_OkClick;
        }

        private void ModelEdit1_OkClick(object? sender, object e)
        {
            OkButtonClick?.Invoke(this, this.Item);
            this.Close();
        }

        private void ModelEdit1_CancelClick(object? sender, object e)
        {
            this.Close();
        }

        public object Item { get; private set; }

        public ItemChangedType ChangedType { get; private set; }

        #region 共有属性

        [Description("确定按钮点击事件")]
        [Category("按钮")]
        public EventHandler<object> OkButtonClick { get; set; }

        #endregion


        private void SetBox()
        {
            var type = this.Item.GetType();
            var properties = type.GetProperties();

            var itembuilder = modelEdit1.GetItemBuilder(Item);

            foreach (var item in properties)
            {
                var displayName = item.GetCustomAttribute<DisplayNameAttribute>();
                var iskey = item.GetCustomAttribute<KeyAttribute>() is not null && ChangedType == ItemChangedType.Update;
                var col = item.GetCustomAttribute<ColAttribute>();
                if (col != null && ((col.IsEdit && ChangedType == ItemChangedType.Update) || (col.IsAdd && ChangedType == ItemChangedType.Add)))
                {
                    if (col.EditTemplate != null)
                    {
                        var lable = col.Name ?? displayName?.DisplayName ?? item.Name;
                        var control = App.GetControlService(col.EditTemplate);
                        itembuilder.Add(item.Name, lable, content: control, action: c => c.Enabled = !iskey);
                    }
                    else
                    {
                        var lable = col.Name ?? displayName?.DisplayName ?? item.Name;
                        itembuilder.Add(item.Name, lable, action: c => c.Enabled = !iskey);
                    }
                }
            }
        }
    }
}
